using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net;
using System.Security.Authentication;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
using iPhOwa.Exchange;
using iPhOwa.Web.Properties;

namespace iPhOwa.Web
{
	/// <summary>
	/// Form for site login.
	/// </summary>
	[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login")]
	public partial class Login : iPhOwaPage
	{
		/// <summary>
		/// Determines if we need to auth for this page.
		/// </summary>
		protected override bool IsSecurePage
		{
			get { return false; }
		}

		/// <summary>
		/// Page_Load Event
		/// </summary>
		protected void Page_Load(object sender, EventArgs e)
		{
            //TODO: This seems hacky, think about a more elegant way to solve this requirement
            if (!Settings.Default.EmailRequired)
            {
                DisableEmailRequirement();
            }

			if(!IsPostBack)
			{
				Title = string.Format(CultureInfo.CurrentUICulture, "Login - {0}", Settings.Default.Title);

				string username = GetCookie(UserNameCookie);
				string password = GetCookie(PasswordCookie);
                string email = GetCookie(UserEmailCookie);

				if(!string.IsNullOrEmpty(username))
				{
					loginControl.UserName = username;
					loginControl.RememberMeSet = true;

                    if (!string.IsNullOrEmpty(email))
                    {
                        ((TextBox)loginControl.FindControl("Email")).Text = email;                        
                    }

					if(!string.IsNullOrEmpty(password))
					{
						try
						{
							Authenticate(username, password, email);

							FormsAuthentication.RedirectFromLoginPage(username, false);
							Response.End();
						}
						catch(HttpException)
						{
							// HACK: we need to add logging and figure out why this eror occurs.
							Response.Redirect(FormsAuthentication.DefaultUrl);
							Response.End();
						}
						catch(AuthenticationException) {}
					}
				}
			}
		}
        /// <summary>
        ///  Hides the Panel with the email requirement controls and disables
        ///  the RequiredFieldValidator that is attached to it
        /// </summary>
        private void DisableEmailRequirement()
        {
            //((TextBox)loginControl.FindControl("Email")).Enabled = false;
            ((TextBox)loginControl.FindControl("Email")).Visible = false;

            ((RequiredFieldValidator)loginControl.FindControl("EmailRequired")).Enabled = false;
            //((Label)loginControl.FindControl("EmailLabel")).Visible = false;

            ((Panel)loginControl.FindControl("EmailPanel")).Visible = false;
        }

		/// <summary>
		/// FormsAuthenticate event.
		/// </summary>
		[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login")]
		[SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
		protected void LoginControl_Authenticate(object sender, AuthenticateEventArgs e)
		{
            string email = ((TextBox)loginControl.FindControl("Email")).Text;

			try
			{
				Authenticate(loginControl.UserName, loginControl.Password, email);

				e.Authenticated = true;
			}
			catch(AuthenticationException)
			{
				e.Authenticated = false;
			}
		}

		/// <summary>
		/// Call OWA for authentication.
		/// </summary>
		[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters",
				MessageId = "System.NotSupportedException.#ctor(System.String)")]
		private void Authenticate(string username, string password, string email)
		{
			if(AuthenticationType == AuthenticationType.Forms)
			{
				CookieContainer cookies = OwaAuthenticator.FormsAuthenticate(Settings.Default.OwaUrl, username, password, email);

				OwaCookies = cookies;
				UserName = username;
                UserEmail = email;
			}
			else
			{
				UserName = username;
				Password = password;
                UserEmail = email;
			}

			if(loginControl.RememberMeSet)
			{
				SetCookie(UserNameCookie, username);
				SetCookie(PasswordCookie, password);
                SetCookie(UserEmailCookie, email);
			}
			else
			{
				ExpireCookie(UserNameCookie);
				ExpireCookie(PasswordCookie);
                ExpireCookie(UserEmailCookie);
			}
		}
	}
}